package com.jason.kotlin.gank.viewmodel

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jason.kotlin.gank.model.RollNewsDetailBean
import com.jason.kotlin.gank.model.RollNewsInfoBean
import com.jason.kotlin.gank.model.RollNewsTypeBean
import com.jason.kotlin.gank.repository.RollApiImpl
import com.jason.library.common.base.BasePageViewModel
import com.jason.library.common.base.DataWrapper
import kotlinx.coroutines.launch

/**
 * @description: RollNewsViewModel
 *
 * @author ChenBaoyang
 * @date 4/28/21 17:47
 */
class RollNewsViewModel(application: Application) : BasePageViewModel<RollNewsInfoBean>(application){

    private val rollApi = RollApiImpl()

    val dataNewsType = MutableLiveData<List<RollNewsTypeBean>>()

    val dataNewsDetail = MutableLiveData<RollNewsDetailBean>()

    var typeId: Int = 0

    override fun loadData(page: Int) {
        viewModelScope.launch {
            try {
                val response = rollApi.getNewsList(typeId, page)
                data.postValue(DataWrapper.success(response.data))
                showContent()
            }catch (e: Exception) {
                showError(e.toString())
            }
        }
    }

    fun loadNewsTypes() {
        viewModelScope.launch {
            showLoading()
            try {
                val response = rollApi.getNewsTypes()
                dataNewsType.postValue(response.data)
                showContent()
            }catch (e: Exception) {
                showError(e.toString())
            }
        }
    }

    fun loadNewsDetail(newsId: Int) {
        viewModelScope.launch {
            showLoading()
            try {
                val response = rollApi.getNewsDetail(newsId)
                dataNewsDetail.postValue(response.data)
                showContent()
            }catch (e: Exception) {
                showError(e.toString())
            }
        }
    }
}